﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using MensUnoShop.Areas.Admin.Models;
using MensUnoShop.Models;
using SenerPro;
using MvcPaging;
using MensUnoShop.Areas.Admin.Filters;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel.Contrib;
using NPOI.SS.Util;
using System.IO;

namespace MensUnoShop.Areas.Admin.Controllers
{
    [ManagerCheckFilter]
    public class OrderManagementController : Controller
    {
        //
        // GET: /Admin/OrderManagement/
        int defaultPageSize = 30;
        private Logger _log = new Logger(Config.logpath);

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]//歷史清單
        public ActionResult OrderList(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                if (page != 0)
                {
                    if (TempData["111"] != null)
                    {
                        foreach (var tt in TempData)
                        {
                            ViewData[tt.Key] = tt.Value;
                        }
                        Session["data"] = ViewData;

                        orderdatalist = (List<OrderData>)ViewData["orderdatalist"];
                    }
                    else
                    {

                        if (Session["data"] != null)
                        {
                            ViewData = (ViewDataDictionary)Session["data"];
                            orderdatalist = (List<OrderData>)ViewData["orderdatalist"];
                        }
                        else
                        {
                            orderdatalist = OrderFactory.GetOrderdataList("queryall", "", "");
                            Session["orderdatalist"] = orderdatalist;//匯出excel用

                            orderdatalist = orderdatalist.
                                Select(o => new OrderData
                                {
                                    OGUID = o.OGUID,
                                    OTXID = o.OTXID,
                                    RCNAME = o.RCNAME,
                                    PAYTYPE = o.PAYTYPE,
                                    OCASHID = o.OCASHID,
                                    ORDERDATE = o.ORDERDATE,
                                    ORDERPRICE = o.ORDERPRICE,
                                    ORDERPAYPRICE = o.ORDERPAYPRICE,
                                    OSTATUS = o.OSTATUS,
                                    MGUID = o.MGUID
                                }).Distinct(new ComparOrderData()).ToList();

                            ViewData["orderdatalist"] = orderdatalist;
                            Session["data"] = ViewData;
                        }
                    }
                }
                else
                {
                    currentPageIndex = 0;
                    orderdatalist = OrderFactory.GetOrderdataList("queryall", "", "");
                    Session["orderdatalist"] = orderdatalist;//匯出excel用

                    orderdatalist = orderdatalist.
                                Select(o => new OrderData
                                {
                                    OGUID = o.OGUID,
                                    OTXID = o.OTXID,
                                    RCNAME = o.RCNAME,
                                    PAYTYPE = o.PAYTYPE,
                                    OCASHID = o.OCASHID,
                                    ORDERDATE = o.ORDERDATE,
                                    ORDERPRICE = o.ORDERPRICE,
                                    ORDERPAYPRICE = o.ORDERPAYPRICE,
                                    OSTATUS = o.OSTATUS,
                                    MGUID = o.MGUID
                                }).Distinct(new ComparOrderData()).ToList();

                    ViewData["orderdatalist"] = orderdatalist;
                    Session["data"] = ViewData;
                }
                return View(orderdatalist.ToPagedList(currentPageIndex, defaultPageSize));
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderList", ex.ToString());
            }
            return View();
            
        }

        [HttpPost]
        public ActionResult GetOrder(FormCollection frm, int? page)
        {
            try
            {                
                TempData["querychoice"] = frm["querychoice"] == null ? "" : frm["querychoice"].Trim().ToString();
                TempData["querycontent"] = frm["querycontent"] == null ? "" : frm["querycontent"].Trim().ToString();
                ViewData["querytype"] = frm["querytype"] == null ? "" : frm["querytype"].Trim().ToString();

                if (ViewData["querytype"].ToString() == "history")
                {
                    List<OrderData> orderdatalist = new List<OrderData>();
                    orderdatalist = OrderFactory.GetOrderdataList(TempData["querychoice"].ToString(), TempData["querycontent"].ToString(), ViewData["querytype"].ToString());
                    ViewData["orderdatalist"] = orderdatalist;
                    Session["orderdatalist"] = orderdatalist;//匯出excel用
                    TempData["orderdatalist"] = orderdatalist;
                    TempData["111"] = "1";


                    return Redirect("OrderList");
                }
                else if (ViewData["querytype"].ToString() == "waiting")
                {
                    List<OrderData> orderdatalist = new List<OrderData>();
                    orderdatalist = OrderFactory.GetOrderdataList(TempData["querychoice"].ToString(), TempData["querycontent"].ToString(), ViewData["querytype"].ToString());
                    
                    ViewData["waitingorderdatalist"] = orderdatalist;
                    Session["waitingorderdatalist"] = orderdatalist;//匯出excel用
                    TempData["waitingorderdatalist"] = orderdatalist;
                    TempData["111"] = "1";

                    return Redirect("OrderListWaiting");
                }
                
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderList", ex.ToString());
            }

            return View();
        }
        
        public ActionResult OrderDetail(Guid id)
        {
            Order o = new Order();
            try
            {
                o = new Order(id);
                o.GetRecipient();
                o.GetOrderMarketList();
                o.GetSimpleDiscount();
                o.GetStatus();
                
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderDetail", ex.ToString());
            }

            return View(o);
        }

        [HttpGet]//待入帳訂單
        public ActionResult OrderListWaiting(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                if (page != 0)
                {
                    if (TempData["111"] != null)
                    {
                        foreach (var tt in TempData)
                        {
                            ViewData[tt.Key] = tt.Value;
                        }
                        Session["data"] = ViewData;

                        orderdatalist = (List<OrderData>)ViewData["waitingorderdatalist"];
                    }
                    else
                    {
                        if (Session["data"] != null)
                        {
                            ViewData = (ViewDataDictionary)Session["data"];
                            orderdatalist = (List<OrderData>)ViewData["waitingorderdatalist"];
                        }
                        else
                        {
                            orderdatalist = OrderFactory.GetOrderdataList("queryall", "", "waiting");
                            Session["waitingorderdatalist"] = orderdatalist;//匯出excel用
                            orderdatalist = orderdatalist.
                                Select(o => new OrderData
                                {
                                    OGUID = o.OGUID,
                                    OTXID = o.OTXID,
                                    MEMAIL = o.MEMAIL,
                                    MNAME = o.MNAME,
                                    OSHIPPINGWAY = o.OSHIPPINGWAY,
                                    PAYTYPE = o.PAYTYPE,
                                    OCASHID = o.OCASHID,
                                    ORDERDATE = o.ORDERDATE,
                                    ORDERPRICE = o.ORDERPRICE,
                                    RCCUSTOMER = o.RCCUSTOMER,
                                    MGUID = o.MGUID
                                }).Distinct(new ComparOrderData()).ToList();

                            ViewData["waitingorderdatalist"] = orderdatalist;
                           
                            Session["data"] = ViewData;
                        }
                    }
                }
                else
                {
                    currentPageIndex = 0;
                    orderdatalist = OrderFactory.GetOrderdataList("queryall", "", "waiting");
                    Session["waitingorderdatalist"] = orderdatalist;//匯出excel用
                    orderdatalist = orderdatalist.
                                Select(o => new OrderData
                                {
                                   OGUID= o.OGUID,
                                   OTXID= o.OTXID,
                                   MEMAIL= o.MEMAIL,
                                   MNAME= o.MNAME,
                                   OSHIPPINGWAY= o.OSHIPPINGWAY,
                                   PAYTYPE= o.PAYTYPE,
                                   OCASHID= o.OCASHID,
                                   ORDERDATE= o.ORDERDATE,
                                   ORDERPRICE= o.ORDERPRICE,
                                   RCCUSTOMER= o.RCCUSTOMER,
                                   MGUID= o.MGUID
                                }).Distinct(new ComparOrderData()).ToList();

                    ViewData["waitingorderdatalist"] = orderdatalist;
                    Session["data"] = ViewData;
                }
                return View(orderdatalist.ToPagedList(currentPageIndex, defaultPageSize));
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderListWaiting", ex.ToString());
            }
            return View();
            
        
        }
        
        [HttpGet]//出貨單
        public ActionResult OrderListPaid()
        {
            
            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                orderdatalist = OrderFactory.GetOrderdataListPayment();
                orderdatalist.Where(m => m.MKTYPE == Config.MarketType.Combo && m.MOKPRICE == 0).ToList().ForEach(m => m.MOKAMOUNT = 1);
                ViewData["orderdatalist"] = orderdatalist;
                Session["orderdatalist"] = orderdatalist;//匯出excel用
                
                //return Redirect("OrderListPaid");
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderListPaid", ex.ToString());
            }
            return View(orderdatalist);


        }

        //匯出記錄
        public ActionResult OrderListShip(FormCollection frm)
        {
            ViewData["sdate"] = frm["sdate"] == null ? DateTime.Today.AddMonths(-1).ToString("MM/dd/yyyy") : frm["sdate"].Trim().ToString();
            ViewData["edate"] = frm["edate"] == null ? DateTime.Today.ToString("MM/dd/yyyy") : frm["edate"].Trim().ToString();
            List<OrderBatch> orderbatchlist = new List<OrderBatch>();
            try
            {
                orderbatchlist = OrderFactory.GetShipBatch(DateTime.Parse(ViewData["sdate"].ToString()), DateTime.Parse(ViewData["edate"].ToString()).AddDays(+1).AddMilliseconds(-1)).OrderByDescending(d => d.OBBATCHID).ToList() ;

                ViewData["orderbatchlist"] = orderbatchlist;
                Session["orderbatchlist"] = orderbatchlist;//匯出excel用

                //return Redirect("OrderListPaid");
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderListShip", ex.ToString());
            }
            return View(orderbatchlist);

        }

        [HttpPost]
        public JsonResult OrderStatusChange(Guid oguid, int orderstatus)
        {
            Order o = OrderFactory.GetOrderByOguid(oguid.ToString());
            
            if (o != null)
            {
                Member m;
                string mailcontent;
                switch (orderstatus)
                {
                    case 0:
                        o.SetStatus(Config.OrderStatusType.Init);
                        break;
                    case 1:
                        o.SetStatus(Config.OrderStatusType.Waiting);
                        break;
                    case 2:
                        o.SetStatus(Config.OrderStatusType.ApplyReturn);
                        break;
                    case 3:
                        o.SetStatus(Config.OrderStatusType.Payment);
                        break;
                    case 4:
                        o.SetStatus(Config.OrderStatusType.Refunding);
                        m = MemberFactory.GetMember(o.MGUID);
                        //發送通知信
                        mailcontent = System.IO.File.ReadAllText(Server.MapPath(Config.Latter_Mail_Order_Return)).Replace("[lastname]", m.LASTNAME);
                        Config.SendMail("確認退貨通知 Notification of your order returned", mailcontent, m.EMAIL, m.FIRSTNAME + "," + m.LASTNAME);
                        break;
                    case 5:
                        o.SetStatus(Config.OrderStatusType.Refunded);
                        m = MemberFactory.GetMember(o.MGUID);
                        //發送通知信
                        mailcontent = System.IO.File.ReadAllText(Server.MapPath(Config.Latter_Mail_Order_Refund)).Replace("[lastname]", m.LASTNAME);
                        Config.SendMail("確認退款通知 Notification of money-returned", mailcontent, m.EMAIL, m.FIRSTNAME + "," + m.LASTNAME);
                        break;
                    case 6:
                        o.SetStatus(Config.OrderStatusType.Fail);
                        break;
                    case 7:
                        o.SetStatus(Config.OrderStatusType.Cannel);
                        break;
                    case 8:
                        o.SetStatus(Config.OrderStatusType.Shipping);
                        break;
                    case 9:
                        o.SetStatus(Config.OrderStatusType.PreShipping);
                        break;
                    default:
                        break;
                }
                return Json(new { code = "200", response = "" });
            }
            else
            {
                return Json(new { code = "400", response = "訂單異常!" });
            }
        }

        public ActionResult OrderDetailView(Guid id)
        {
            Order o = new Order();
            try
            {
                o = new Order(id);
                o.GetRecipient();
                o.GetOrderMarketList();
                if (o.MLIST.Any(m => m.TYPE == Config.MarketType.Combo))
                {
                    List<OrderMarket> newlist = new List<OrderMarket>();
                    foreach (var mk in o.MLIST.Where(m => m.PRICE > 0 && m.TYPE == Config.MarketType.Combo))
                    {
                        OrderMarket om = new OrderMarket();
                        om.AMOUNT = mk.AMOUNT;
                        om.COLOR = "合購商品";
                        om.COMBOID = mk.COMBOID;
                        om.MOKGUID = Guid.NewGuid();
                        om.PRICE = mk.PRICE;
                        om.SINGLEPRICE = mk.SINGLEPRICE;
                        om.SN = "";
                        om.SPECID = mk.SPECID;
                        Tag t = TagFactory.GetTag(mk.COMBOID);
                        if (t != null)
                            om.TITLE = t.TITLE;
                        om.TYPE = Config.MarketType.Combo;
                        newlist.Add(om);
                        mk.AMOUNT = 0;
                        mk.SINGLEPRICE = 0;
                        mk.PRICE = 0;
                    }
                    o.MLIST.AddRange(newlist);
                }
                o.GetSimpleDiscount();
                o.GetStatus();

            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderDetailView", ex.ToString());
            }

            return View(o);
        }

        [HttpPost]
        public JsonResult OrderShip(string oguid, string changeordership)
        {
            Member m;
            string mailcontent;
            try
            {
                if (changeordership == "1")
                {
                    Order o = OrderFactory.GetOrderByOguid(oguid.ToString());
                    string batchid = DateTime.Now.ToString("yyyyMMddHHmmss");
                    if (o != null)
                    {
                        if (OrderFactory.CreateOrderBatchData(batchid, new Guid(oguid), DateTime.Now))
                        {
                            o.SetStatus(Config.OrderStatusType.PreShipping);
                            m = MemberFactory.GetMember(o.MGUID);
                            //發送通知信
                            mailcontent = System.IO.File.ReadAllText(Server.MapPath(Config.Latter_Mail_Order_Shipping)).Replace("[lastname]", m.LASTNAME);
                            Config.SendMail("出貨通知 Notification of your shipping sent", mailcontent, m.EMAIL, m.FIRSTNAME + "," + m.LASTNAME);
                            return Json(new { code = "200", response = "" });
                        }
                        else
                            return Json(new { code = "400", response = "資料重複!" });
                    }
                    else
                    {
                        return Json(new { code = "400", response = "異常!" });
                    }
                }
                else if (changeordership == "2")
                {
                    string[] aa = oguid.Split('.');
                    string bb = string.Empty;
                    for (int i = 0; i < aa.Length; i++)
                    {
                        if (!bb.Contains(aa[i].ToString()))
                        {
                            bb += aa[i].ToString() + ",";
                        }
                    }
                    
                    bb = bb.Remove(bb.Length - 1);                    
                    string[] cc = bb.Split(',');
                    bool status = true;
                    string batchid = DateTime.Now.ToString("yyyyMMddHHmmss");
                    DateTime batchdate = DateTime.Now;
                    string err = string.Empty;
                    for (int i = 0; i < cc.Length; i++)
                    {
                        Order o = OrderFactory.GetOrderByOguid(cc[i].ToString());//new Order(new Guid(cc[i].ToString())); 
                        if (o != null)
                        {                            
                            if (OrderFactory.CreateOrderBatchData(batchid, new Guid(cc[i].ToString()), batchdate))
                            {
                                o.SetStatus(Config.OrderStatusType.PreShipping);
                                m = MemberFactory.GetMember(o.MGUID);
                                //發送通知信
                                mailcontent = System.IO.File.ReadAllText(Server.MapPath(Config.Latter_Mail_Order_Shipping)).Replace("[lastname]", m.LASTNAME);
                                Config.SendMail("出貨通知 Notification of your shipping sent", mailcontent, m.EMAIL, m.FIRSTNAME + "," + m.LASTNAME);
                            }
                            else
                            {
                                status = false;
                                err = "1";
                                break;
                            }
                        }
                        else
                        {
                            status = false;
                            err = "2";
                            break;
                        }
                    }

                    if (status)
                    {
                        return Json(new { code = "200", response = "" });
                    }
                    else
                    {
                        return Json(new { code = "400", response = "資料錯誤"+err });
                    }

                }
                else
                    return Json(new { code = "400", response = "異常!" });
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderShip", ex.ToString());

            }
            return Json(new { code = "400", response = "異常!" });
        }

        public ActionResult GetExcel(string id)
        {
            List<OrderData> orderdatalist = new List<OrderData>();
            if (id == "WaitingList" || id == "HistoryList")
            {
                if (Session["waitingorderdatalist"] != null)
                {
                    List<OrderData>  orderdatalisttemp = (List<OrderData>)Session["waitingorderdatalist"];

                    foreach (var item in orderdatalisttemp)
                    {
                        OrderData od = new OrderData();
                        od = item;

                        orderdatalist.Add(od);
                    }
                }
                if (Session["orderdatalist"] != null)
                {
                    List<OrderData> orderdatalisttemp = (List<OrderData>)Session["orderdatalist"];

                    foreach (var item in orderdatalisttemp)
                    {
                        OrderData od = new OrderData();
                        od = item;

                        orderdatalist.Add(od);
                    }
                }
            }
            else
            {
                string sortindex = Request.Params["sortindex"] == null ? "orderdate" : Request.Params["sortindex"].ToString();
                string sorttype = Request.Params["sorttype"] == null ? "desc" : Request.Params["sorttype"].ToString();
                string sort = string.Empty;
                switch (sortindex)
                {
                    case "orderdate":
                        sort = "vod.Oorderdate ";
                        break;
                    case "statusdate":
                        sort = "vod.Ostatusdatein ";
                        break;
                    case "txid":
                        sort = "vod.Otxid ";
                        break;
                    case "cashid":
                        sort = "vod.Ocashid ";
                        break;
                    default:
                        sort = "vod.Oorderdate ";
                        break;
                }
                orderdatalist = OrderFactory.GetOrderdataListShipBatch(id, sort + sorttype);
            }
                        

            if (orderdatalist != null)
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                if (id == "WaitingList")
                {
                    HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("待入帳明細");

                    Row row;
                    row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("訂單編號");
                    row.CreateCell(1).SetCellValue("會員帳號(E-Mail)");
                    row.CreateCell(2).SetCellValue("會員姓名");
                    row.CreateCell(3).SetCellValue("消費金額	");
                    row.CreateCell(4).SetCellValue("運送方式");
                    row.CreateCell(5).SetCellValue("付費方式	");
                    row.CreateCell(6).SetCellValue("金流編號");
                    row.CreateCell(7).SetCellValue("訂單日期");

                    HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
                    HSSFCellStyle styleDate = (HSSFCellStyle)workbook.CreateCellStyle();
                    styleDate.DataFormat = format.GetFormat("yyyy-mm-dd");
                    sheet.SetColumnWidth(5, 15 * 256);
                    sheet.SetColumnWidth(13, 15 * 256);
                    int count = 1;
                    foreach (OrderData od in orderdatalist)
                    {
                        row = sheet.CreateRow(count);
                        //Order o = of.GetOrderByTxid(so.OTXID);
                        //if (o != null)
                        //{
                        //o.GetRecipient();

                        row.CreateCell(0).SetCellValue(od.OTXID);                        
                        row.CreateCell(1).SetCellValue(od.MEMAIL);
                        row.CreateCell(2).SetCellValue(od.MNAME);
                        row.CreateCell(3).SetCellValue(od.ORDERPRICE);
                        row.CreateCell(4).SetCellValue(GetShippingWay(od.OSHIPPINGWAY));
                        row.CreateCell(5).SetCellValue(od.PAYTYPE.ToString());
                        row.CreateCell(6).SetCellValue(od.OCASHID);
                        row.CreateCell(7).SetCellValue(od.ORDERDATE.ToString());
                        
                        count++;

                        //}
                        //else
                        //    count++;
                    }
                }
                else if (id == "HistoryList")
                {
                    HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("歷史清單");

                    Row row;
                    row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("訂單編號");
                    row.CreateCell(1).SetCellValue("金流編號");
                    row.CreateCell(2).SetCellValue("會員姓名");
                    row.CreateCell(3).SetCellValue("商品貨號");
                    row.CreateCell(4).SetCellValue("商品名稱");
                    row.CreateCell(5).SetCellValue("顏色");
                    row.CreateCell(6).SetCellValue("尺寸");
                    row.CreateCell(7).SetCellValue("數量");
                    row.CreateCell(8).SetCellValue("運送方式");
                    row.CreateCell(9).SetCellValue("商品價格");
                    row.CreateCell(10).SetCellValue("運費");
                    row.CreateCell(11).SetCellValue("客戶意見欄");
                    row.CreateCell(12).SetCellValue("收件者姓名");
                    row.CreateCell(13).SetCellValue("收件者電話");
                    row.CreateCell(14).SetCellValue("收件者地址");
                    row.CreateCell(15).SetCellValue("發票類型");
                    row.CreateCell(16).SetCellValue("入帳時間");
                    row.CreateCell(17).SetCellValue("付款方式");
                    row.CreateCell(18).SetCellValue("出貨單號");
                    row.CreateCell(19).SetCellValue("訂單狀態");

                    HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
                    HSSFCellStyle styleDate = (HSSFCellStyle)workbook.CreateCellStyle();
                    styleDate.DataFormat = format.GetFormat("yyyy-mm-dd");
                    sheet.SetColumnWidth(5, 15 * 256);
                    sheet.SetColumnWidth(13, 15 * 256);
                    int count = 1;
                    foreach (OrderData od in orderdatalist)
                    {
                        row = sheet.CreateRow(count);                        

                        row.CreateCell(0).SetCellValue(od.OTXID);
                        row.CreateCell(1).SetCellValue(od.OCASHID);
                        row.CreateCell(2).SetCellValue(od.MNAME);
                        row.CreateCell(3).SetCellValue(od.MOKSN);
                        row.CreateCell(4).SetCellValue(od.MOKTITLE);
                        row.CreateCell(5).SetCellValue(od.COLOR);
                        row.CreateCell(6).SetCellValue(od.SPEC);
                        row.CreateCell(7).SetCellValue(od.MOKAMOUNT);
                        row.CreateCell(8).SetCellValue(GetShippingWay(od.OSHIPPINGWAY));
                        row.CreateCell(9).SetCellValue(od.MOKPRICE);
                        row.CreateCell(10).SetCellValue(od.ODELIVERY);
                        row.CreateCell(11).SetCellValue(od.RCCUSTOMER);
                        row.CreateCell(12).SetCellValue(od.RCNAME);
                        row.CreateCell(13).SetCellValue(od.RCTEL);
                        row.CreateCell(14).SetCellValue(od.RCCOUNTRY + od.RCZIP + od.RCCITY + od.RCAREA + od.RCADDRESS);
                        row.CreateCell(15).SetCellValue(GetInvoiceType(od.OINVOICETYPE));
                        row.CreateCell(16).SetCellValue(od.OSTATUSDATEIN.ToString());
                        row.CreateCell(17).SetCellValue(od.PAYTYPE.ToString());
                        row.CreateCell(18).SetCellValue(od.OSHIPPINGNUM);
                        row.CreateCell(19).SetCellValue(MensUnoShop.Models.Config.GetEnumDescription((MensUnoShop.Models.Config.OrderStatusType)od.OSTATUS.Value));
                        count++;
                       
                    }
                }
                else
                {
                    HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("出貨明細");

                    Row row;
                    row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("訂單編號");
                    row.CreateCell(1).SetCellValue("金流編號");
                    row.CreateCell(2).SetCellValue("會員姓名");
                    row.CreateCell(3).SetCellValue("商品貨號");
                    row.CreateCell(4).SetCellValue("商品名稱");
                    row.CreateCell(5).SetCellValue("顏色");
                    row.CreateCell(6).SetCellValue("尺寸");
                    row.CreateCell(7).SetCellValue("數量");
                    row.CreateCell(8).SetCellValue("運送方式");
                    row.CreateCell(9).SetCellValue("商品價格");
                    row.CreateCell(10).SetCellValue("運費");
                    row.CreateCell(11).SetCellValue("客戶意見欄");
                    row.CreateCell(12).SetCellValue("收件者姓名");
                    row.CreateCell(13).SetCellValue("收件者電話");
                    row.CreateCell(14).SetCellValue("收件者地址");
                    row.CreateCell(15).SetCellValue("發票類型");
                    row.CreateCell(16).SetCellValue("發票抬頭");
                    row.CreateCell(17).SetCellValue("發票統編");
                    row.CreateCell(18).SetCellValue("入帳時間");
                    row.CreateCell(19).SetCellValue("付款方式");
                    row.CreateCell(20).SetCellValue("出貨單號");

                    HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
                    HSSFCellStyle styleDate = (HSSFCellStyle)workbook.CreateCellStyle();
                    styleDate.DataFormat = format.GetFormat("yyyy-mm-dd");
                    sheet.SetColumnWidth(5, 15 * 256);
                    sheet.SetColumnWidth(13, 15 * 256);
                    int count = 1;
                    foreach (OrderData od in orderdatalist)
                    {
                        row = sheet.CreateRow(count);

                        row.CreateCell(0).SetCellValue(od.OTXID);
                        row.CreateCell(1).SetCellValue(od.OCASHID);
                        row.CreateCell(2).SetCellValue(od.MNAME);
                        row.CreateCell(3).SetCellValue(od.MOKSN);
                        row.CreateCell(4).SetCellValue(od.MOKTITLE);
                        row.CreateCell(5).SetCellValue(od.COLOR);
                        row.CreateCell(6).SetCellValue(od.SPEC);
                        row.CreateCell(7).SetCellValue(od.MOKAMOUNT);
                        row.CreateCell(8).SetCellValue(GetShippingWay(od.OSHIPPINGWAY));
                        row.CreateCell(9).SetCellValue(od.MOKPRICE);
                        row.CreateCell(10).SetCellValue(od.ODELIVERY);
                        row.CreateCell(11).SetCellValue(od.RCCUSTOMER);
                        row.CreateCell(12).SetCellValue(od.RCNAME);
                        row.CreateCell(13).SetCellValue(od.RCTEL);
                        row.CreateCell(14).SetCellValue(od.RCCOUNTRY + od.RCZIP + od.RCCITY + od.RCAREA + od.RCADDRESS);
                        row.CreateCell(15).SetCellValue(GetInvoiceType(od.OINVOICETYPE));
                        row.CreateCell(16).SetCellValue(od.OINVOICETITLE);
                        row.CreateCell(17).SetCellValue(od.OINVOICESERIAL);
                        row.CreateCell(18).SetCellValue(od.OSTATUSDATEIN.ToString());
                        row.CreateCell(19).SetCellValue(od.PAYTYPE.ToString());
                        row.CreateCell(20).SetCellValue(od.OSHIPPINGNUM);

                        count++;

                        //}
                        //else
                        //    count++;
                    }
                }
                

                workbook.Write(ms);
                workbook = null;
                Session["olist"] = null;

                return File(ms.GetBuffer(), "application/vnd.ms-excel", id + ".xls");
            }
            else
                return Redirect("OrderListShip");
        }

        public ActionResult OrderShipBatchDetail(string id, int? page)
        {
            ViewData["batchid"] = id;
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            string sortindex = Request.Params["sortindex"] == null ? "orderdate" : Request.Params["sortindex"].ToString();
            string sorttype = Request.Params["sorttype"] == null ? "desc" : Request.Params["sorttype"].ToString();
            string sort = string.Empty;            
            switch (sortindex)
            {
                case "orderdate":
                    sort = "vod.Oorderdate ";
                    break;                
                case "statusdate":
                    sort = "vod.Ostatusdatein ";
                    break;
                case "txid":
                    sort = "vod.Otxid ";
                    break;
                case "cashid":
                    sort = "vod.Ocashid ";
                    break;
                default:
                    sort = "vod.Oorderdate ";
                    break;
            }
            if (sorttype == "asc")
            {
                ViewData["sorttype"] = "desc";
            }
            else
            {
                ViewData["sorttype"] = "asc";
            }

            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                orderdatalist = OrderFactory.GetOrderdataListShipBatch(id, sort + sorttype);
                orderdatalist.Where(m => m.MKTYPE == Config.MarketType.Combo && m.MOKPRICE == 0).ToList().ForEach(m => m.MOKAMOUNT = 1);
                if (orderdatalist.Any(m => m.MKTYPE == Config.MarketType.Combo))
                {
                    List<OrderData> newlist = new List<OrderData>();
                    foreach (var mk in orderdatalist.Where(m => m.MOKPRICE > 0 && m.MKTYPE == Config.MarketType.Combo))
                    {
                        OrderData om = new OrderData();
                        om.COLOR = "合購商品";
                        om.MEMAIL = mk.MEMAIL;
                        om.MGUID = mk.MGUID;
                        om.MKTYPE = Config.MarketType.Combo;
                        om.MNAME = mk.MNAME;
                        om.MOKAMOUNT = mk.MOKAMOUNT;
                        om.MOKCOMBOOID = mk.MOKCOMBOOID;
                        om.MOKPRICE = mk.MOKPRICE;
                        om.MOKSINGLEPRICE = mk.MOKSINGLEPRICE;
                        om.MOKSN = "";
                        om.OSHIPPINGWAY = mk.OSHIPPINGWAY;
                        om.OTXID = mk.OTXID;
                        om.RCADDRESS = mk.RCADDRESS;
                        om.RCAREA = mk.RCAREA;
                        om.RCCITY = mk.RCCITY;
                        om.RCCOUNTRY = mk.RCCOUNTRY;
                        om.RCCUSTOMER = mk.RCCUSTOMER;
                        om.RCNAME = mk.RCNAME;
                        om.RCTEL = mk.RCTEL;
                        om.RCZIP = mk.RCZIP;
                        
                        Tag t = TagFactory.GetTag(mk.MOKCOMBOOID);
                        if (t != null)
                            om.MOKTITLE = t.TITLE;
                        om.OBBATCHID = mk.OBBATCHID;
                        om.OCASHID = mk.OCASHID;
                        om.ODELIVERY = mk.ODELIVERY;
                        om.OGUID = mk.OGUID;
                        om.OINVOICESERIAL = mk.OINVOICESERIAL;
                        om.OINVOICETITLE = mk.OINVOICETITLE;
                        om.OINVOICETYPE = mk.OINVOICETYPE;
                        om.ORDERDATE = mk.ORDERDATE;
                        om.ORDERPAYDATE = mk.ORDERPAYDATE;
                        om.ORDERPAYPRICE = mk.ORDERPAYPRICE;
                        om.ORDERPRICE = mk.ORDERPRICE;
                        om.OSHIPPINGNUM = mk.OSHIPPINGNUM;
                        om.OSHIPPINGWAY = mk.OSHIPPINGWAY;
                        newlist.Add(om);

                        mk.MOKAMOUNT = 1;
                        mk.MOKPRICE = 0;
                        mk.MOKSINGLEPRICE = 0;
                    }
                    orderdatalist.AddRange(newlist);
                }
                orderdatalist = orderdatalist.OrderBy(m=>m.OTXID).ThenBy(m => m.MOKCOMBOOID).ThenByDescending(m=>m.MOKPRICE).ToList();

                ViewData["orderdatalist"] = orderdatalist;
                Session["orderdatalist"] = orderdatalist;//匯出excel用

            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderShipBatchDetail", ex.ToString());
            }
            return View(orderdatalist.ToPagedList(currentPageIndex, defaultPageSize));
        }

        public ActionResult OrderShipPaper(string id)
        {
            ViewData["batchid"] = id;
            List<Order> orderlist = new List<Order>();
            List<OrderData> orderdatalist = new List<OrderData>();
            Logger log = new Logger(Config.logpath);
            try
            {
                orderdatalist = OrderFactory.GetOrderdataListShipBatch(id, "");
                string txid = string.Empty;
                //log.RecordException(log.FlowLogPath, orderdatalist.Count.ToString());
                foreach (var item in orderdatalist)
                {
                    //log.RecordException(log.FlowLogPath, item.OTXID);
                    Order o = OrderFactory.GetOrderByTxid(item.OTXID);
                    if (o != null && !orderlist.Any(oo => oo.TXID == item.OTXID))
                    {
                        o.GetOrderMarketList();
                        o.MLIST.Where(m => m.TYPE == Config.MarketType.Combo && m.PRICE == 0).ToList().ForEach(m => m.AMOUNT = 1);
                        if (o.MLIST.Any(m => m.TYPE == Config.MarketType.Combo))
                        {
                            List<OrderMarket> newlist = new List<OrderMarket>();
                            foreach (var mk in o.MLIST.Where(m => m.PRICE > 0 && m.TYPE == Config.MarketType.Combo))
                            {
                                OrderMarket om = new OrderMarket();
                                om.AMOUNT = mk.AMOUNT;
                                om.COLOR = "合購商品";
                                om.COMBOID = mk.COMBOID;
                                om.MOKGUID = Guid.NewGuid();
                                om.PRICE = mk.PRICE;
                                om.SINGLEPRICE = mk.SINGLEPRICE;
                                om.SN = "";
                                om.SPECID = mk.SPECID;
                                Tag t = TagFactory.GetTag(mk.COMBOID);
                                if (t != null)
                                    om.TITLE = t.TITLE;
                                om.TYPE = Config.MarketType.Combo;
                                newlist.Add(om);
                                mk.AMOUNT = 1;
                                mk.SINGLEPRICE = 0;
                                mk.PRICE = 0;
                            }
                            o.MLIST.AddRange(newlist);
                        }


                        o.GetRecipient();
                        o.GetSimpleDiscount();
                        o.GetStatus();
                        

                        if (o.STATUSLIST.FirstOrDefault(ss => ss.Ostatus == MensUnoShop.Models.Config.OrderStatusType.Shipping) != null)
                            o.SHIPPINGDATE = o.STATUSLIST.FirstOrDefault(ss => ss.Ostatus == MensUnoShop.Models.Config.OrderStatusType.Shipping).Ochangedate;
                        else
                            o.SHIPPINGDATE = o.STATUSLIST.LastOrDefault().Ochangedate;

                        orderlist.Add(o);
                    }                        
                }
                //log.RecordException(log.FlowLogPath, orderlist.Count.ToString());
                //ViewData["orderdatalist"] = orderdatalist;
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderShipPaper", ex.ToString());
            }
            return View(orderlist);
        }

        [HttpGet]
        public ActionResult OrderShippingnumChange(string id)
        {
            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                orderdatalist = OrderFactory.GetOrderdata(new Guid(id));

            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderShippingnumChange", ex.ToString());
            }
            return View(orderdatalist);
        }

        [HttpPost]
        public JsonResult OrderShippingnumChange(string oguid, string shippingnum)
        {
            try
            {
                if (OrderFactory.UpdateOrderShippingnum(new Guid(oguid), shippingnum))
                {
                    Order o = OrderFactory.GetOrderByOguid(oguid);

                    if (o != null)
                    {
                        if (o.STATUS == Config.OrderStatusType.PreShipping)
                        {
                            o.SetStatus(Config.OrderStatusType.Shipping);
                        }                        
                        return Json(new { code = "200", response = "" });
                    }
                    else
                        return Json(new { code = "400", response = "更新失敗!" });                    
                }
                else
                    return Json(new { code = "400", response = "更新失敗!" });

            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderShippingnumChange", ex.ToString());

            }
            return Json(new { code = "400", response = "異常!" });
        }

        //退貨清單
        public ActionResult OrderListReturning(FormCollection frm)
        {
            ViewData["sdate"] = frm["sdate"] == null ? DateTime.Today.ToString("MM/dd/yyyy") : frm["sdate"].Trim().ToString();
            ViewData["edate"] = frm["edate"] == null ? DateTime.Today.ToString("MM/dd/yyyy") : frm["edate"].Trim().ToString();
            List<OrderData> orderdatalist = new List<OrderData>();
            try
            {
                orderdatalist = OrderFactory.GetOrderdataListReturning(DateTime.Parse(ViewData["sdate"].ToString()).AddDays(-1).AddMilliseconds(1), DateTime.Parse(ViewData["edate"].ToString()).AddDays(+1).AddMilliseconds(-1));

                ViewData["orderdatalist"] = orderdatalist;
                Session["orderdatalist"] = orderdatalist;//匯出excel用

                //return Redirect("OrderListPaid");
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "OrderListReturning", ex.ToString());
            }
            return View(orderdatalist);


        }
         


        private static string GetShippingWay(int? shippingway)
        {
            string returnStr = string.Empty;
            switch (shippingway)
            {
                case 0:
                    returnStr = "台灣地區免運費 (限時掛號、包裹)";
                    break;
                case 1:
                    returnStr = "亞洲Asia(EMS/國際快捷郵件)";
                    break;
                case 2:
                    returnStr = "美洲或歐洲America and Europe(EMS/國際快捷郵件)";
                    break;
                case 3:
                    returnStr = "中美洲或歐洲America and Europe(EMS/國際快捷郵件)";
                    break;
                default:
                    returnStr = "";
                    break;
            }
            return returnStr;
        }

        private static string GetInvoiceType(int invoicetype)
        {
            string returnStr = string.Empty;
            switch (invoicetype)
            {
                case 0:
                    returnStr = "二聯式";
                    break;
                case 1:
                    returnStr = "三聯式";
                    break;
                default:
                    returnStr = "";
                    break;
            }
            return returnStr;
        }
    }
}
